<template>
    <view class="address-container">
        <!-- 地址列表 -->
        <view class="address-list" v-if="addressList.length > 0">
            <view class="address-item" 
                  v-for="(item, index) in addressList" 
                  :key="item.id"
                  :class="{'active': item.isDefault}">
                <view class="address-info">
                    <view class="name-phone">
                        <text class="name">{{ item.name }}</text>
                        <text class="phone">{{ item.phone }}</text>
                    </view>
                    <view class="address-detail">
                        <text>{{ item.area.join(' ') }}</text>
                        <text class="detail">{{ item.detail }}</text>
                    </view>
                </view>
                <view class="address-actions">
                    <view class="default-tag" v-if="item.isDefault">默认地址</view>
                    <view class="edit-delete">
                        <text @click="editAddress(item.id)">编辑</text>
                        <text @click="deleteAddress(item.id)">删除</text>
                    </view>
                </view>
            </view>
        </view>
        
        <!-- 空地址提示 -->
        <view class="empty-address" v-else>
            <image src="/static/images/empty-address.png" mode="aspectFit"></image>
            <text>暂无收货地址</text>
            <button class="add-btn" @click="addAddress">添加地址</button>
        </view>
        
        <!-- 添加/编辑地址弹窗 -->
        <view class="address-modal" v-if="showModal">
            <view class="modal-content">
                <view class="modal-header">
                    <text>{{ isEdit ? '编辑地址' : '添加地址' }}</text>
                    <text class="close" @click="closeModal">×</text>
                </view>
                <view class="modal-body">
                    <view class="form-item">
                        <text>收货人</text>
                        <input v-model="formData.name" placeholder="请输入收货人姓名" />
                    </view>
                    <view class="form-item">
                        <text>手机号码</text>
                        <input v-model="formData.phone" placeholder="请输入手机号码" type="number" />
                    </view>
                    <view class="form-item area-select" @click="selectArea">
                        <text>所在地区</text>
                        <view class="selected-area">
                            <text>{{ formData.area.join(' ') || '请选择省市区' }}</text>
                            <image src="/static/images/arrow-down.png" mode="aspectFit"></image>
                        </view>
                    </view>
                    <view class="form-item">
                        <text>详细地址</text>
                        <textarea v-model="formData.detail" placeholder="请输入详细地址" />
                    </view>
                    <view class="form-item checkbox">
                      <checkbox-group v-model="formData.isDefault">
                        <label class="checkbox-label">
                          <checkbox value="true" color="#E64340" />
                          <text>设为默认地址</text>
                        </label>
                      </checkbox-group>
                    </view>
                </view>
                <view class="modal-footer">
                    <button class="save-btn" @click="saveAddress">保存地址</button>
                </view>
            </view>
        </view>
        
        <!-- 地区选择器 -->
        <view class="area-picker" v-if="showAreaPicker">
            <view class="picker-header">
                <text class="cancel" @click="cancelArea">取消</text>
                <text class="confirm" @click="confirmArea">确定</text>
            </view>
            <view class="picker-tabs">
                <view class="tab" 
                      :class="{'active': currentTab === 0}" 
                      @click="changeTab(0)">
                    省份
                </view>
               <view class="tab" 
                     :class="{'active': currentTab === 1}" 
                     @click="changeTab(1)"
                     :style="{'opacity': regions.provinces.length === 0 ? 0.5 : 1}"
                     :disabled="regions.provinces.length === 0">
                   城市
               </view>
               <view class="tab" 
                     :class="{'active': currentTab === 2}" 
                     @click="changeTab(2)"
                     :style="{'opacity': (regions.cities[getProvinceCode()] || []).length === 0 ? 0.5 : 1}"
                     :disabled="(regions.cities[getProvinceCode()] || []).length === 0">
                   区县
               </view>
            </view>
            <view class="picker-content">
                <scroll-view scroll-y class="area-list">
                    <view class="area-item" 
                          v-for="(item, index) in currentList" 
                          :key="index"
                          :class="{'selected': isSelected(item.name)}"
                          @click="selectAreaItem(item.name)">
                        {{ item.name }}
                    </view>
                </scroll-view>
            </view>
        </view>
        
        <!-- 添加地址按钮 -->
        <button class="add-address-btn" @click="addAddress" v-if="addressList.length > 0">
            + 添加新地址
        </button>
    </view>
</template>

<script>
export default {
    data() {
        return {
            // 地址列表
            addressList: [
                {
                    id: 1,
                    name: '张三',
                    phone: '13800138000',
                    area: ['广东省', '深圳市', '南山区'],
                    detail: '科技园南区8栋501',
                    isDefault: true
                },
                {
                    id: 2,
                    name: '李四',
                    phone: '13900139000',
                    area: ['北京市', '北京市', '朝阳区'],
                    detail: '建国路88号SOHO现代城B座1502',
                    isDefault: false
                }
            ],
            // 显示添加/编辑地址弹窗
            showModal: false,
            // 是否为编辑状态
            isEdit: false,
            // 当前编辑的地址ID
            currentId: null,
            // 表单数据
            formData: {
                name: '',
                phone: '',
                area: [],
                detail: '',
                isDefault: false
            },
            // 显示地区选择器
            showAreaPicker: false,
            // 当前选择的标签页(0:省份 1:城市 2:区县)
            currentTab: 0,
            // 模拟省市区数据
            regions: {
                provinces: [
                    { name: '北京市', code: '110000' },
                    { name: '上海市', code: '310000' },
                    { name: '广东省', code: '440000' },
                    { name: '江苏省', code: '320000' },
                    { name: '浙江省', code: '330000' }
                ],
                cities: {
                    '110000': [
                        { name: '北京市', code: '110100' }
                    ],
                    '310000': [
                        { name: '上海市', code: '310100' }
                    ],
                    '440000': [
                        { name: '广州市', code: '440100' },
                        { name: '深圳市', code: '440300' },
                        { name: '佛山市', code: '440600' }
                    ],
                    '320000': [
                        { name: '南京市', code: '320100' },
                        { name: '苏州市', code: '320500' },
                        { name: '无锡市', code: '320200' }
                    ],
                    '330000': [
                        { name: '杭州市', code: '330100' },
                        { name: '宁波市', code: '330200' },
                        { name: '温州市', code: '330300' }
                    ]
                },
                districts: {
                    '440300': [
                        { name: '福田区', code: '440304' },
                        { name: '罗湖区', code: '440303' },
                        { name: '南山区', code: '440305' },
                        { name: '宝安区', code: '440306' }
                    ],
                    '110100': [
                        { name: '东城区', code: '110101' },
                        { name: '西城区', code: '110102' },
                        { name: '朝阳区', code: '110105' },
                        { name: '海淀区', code: '110108' }
                    ]
                }
            }
        }
    },
    computed: {
        // 当前显示的列表数据
        currentList() {
            if (this.currentTab === 0) {
                return this.regions.provinces;
            } else if (this.currentTab === 1) {
                const provinceCode = this.getProvinceCode();
                return this.regions.cities[provinceCode] || [];
            } else {
                const cityCode = this.getCityCode();
                return this.regions.districts[cityCode] || [];
            }
        },
      
    },
    methods: {
        // 添加地址
        addAddress() {
            this.isEdit = false;
            this.currentId = null;
            this.formData = {
                name: '',
                phone: '',
                area: [],
                detail: '',
                isDefault: false
            };
            this.showModal = true;
        },
        // 获取省份编码
        getProvinceCode() {
            const province = this.formData.area[0];
            const provinceItem = this.regions.provinces.find(item => item.name === province);
            return provinceItem ? provinceItem.code : '';
        },
        // 获取城市编码
        getCityCode() {
            const city = this.formData.area[1];
            const provinceCode = this.getProvinceCode();
            const cityList = this.regions.cities[provinceCode] || [];
            const cityItem = cityList.find(item => item.name === city);
            return cityItem ? cityItem.code : '';
        },
        // 编辑地址
        editAddress(id) {
            this.isEdit = true;
            this.currentId = id;
            const address = this.addressList.find(item => item.id === id);
            if (address) {
                this.formData = { ...address };
            }
            this.showModal = true;
        },
        
        // 删除地址
        deleteAddress(id) {
            uni.showModal({
                title: '提示',
                content: '确定要删除这个地址吗？',
                success: (res) => {
                    if (res.confirm) {
                        this.addressList = this.addressList.filter(item => item.id !== id);
                        uni.showToast({
                            title: '删除成功',
                            icon: 'success'
                        });
                    }
                }
            });
        },
        
        // 关闭弹窗
        closeModal() {
            this.showModal = false;
        },
        
        // 保存地址
        saveAddress() {
            // 表单验证
            if (!this.formData.name) {
                uni.showToast({
                    title: '请输入收货人姓名',
                    icon: 'none'
                });
                return;
            }
            
            if (!this.formData.phone) {
                uni.showToast({
                    title: '请输入手机号码',
                    icon: 'none'
                });
                return;
            }
            
            if (!/^1[3-9]\d{9}$/.test(this.formData.phone)) {
                uni.showToast({
                    title: '手机号码格式不正确',
                    icon: 'none'
                });
                return;
            }
            
            if (this.formData.area.length === 0) {
                uni.showToast({
                    title: '请选择所在地区',
                    icon: 'none'
                });
                return;
            }
            
            if (!this.formData.detail) {
                uni.showToast({
                    title: '请输入详细地址',
                    icon: 'none'
                });
                return;
            }
            
            // 如果设为默认地址，则将其他地址设为非默认
            if (this.formData.isDefault) {
                this.addressList.forEach(item => {
                    item.isDefault = false;
                });
            }
            
            // 保存地址
            if (this.isEdit) {
                // 编辑地址
                const index = this.addressList.findIndex(item => item.id === this.currentId);
                if (index !== -1) {
                    this.addressList.splice(index, 1, this.formData);
                }
            } else {
                // 新增地址
                const newId = this.addressList.length > 0 ? 
                    Math.max(...this.addressList.map(item => item.id)) + 1 : 1;
                this.addressList.push({
                    ...this.formData,
                    id: newId
                });
            }
            
            this.showModal = false;
            uni.showToast({
                title: this.isEdit ? '编辑成功' : '添加成功',
                icon: 'success'
            });
        },
        
        // 选择地区
        selectArea() {
            this.showModal = false;
            this.showAreaPicker = true;
            this.currentTab = 0;
        },
        
        // 取消选择地区
        cancelArea() {
            this.showAreaPicker = false;
        },
        
        // 确认选择地区
        confirmArea() {
            if (this.formData.area.length < 3) {
                uni.showToast({
                    title: '请选择完整的省市区',
                    icon: 'none'
                });
                return;
            }
            this.showAreaPicker = false;
            this.showModal = true;
        },
        
        // 切换标签页
        changeTab(tabIndex) {
            // 如果没有选择上一级地区，则不能切换到下一级
            if ((tabIndex === 1 && this.formData.area.length === 0) || 
                (tabIndex === 2 && this.formData.area.length < 2)) {
                return;
            }
            this.currentTab = tabIndex;
        },
        
        // 选择地区项
        selectAreaItem(name) {
            // 复制当前已选区域
            const newArea = [...this.formData.area];
            
            // 根据当前标签页更新对应层级的区域
            if (this.currentTab === 0) {
                // 选择省份时，清空城市和区县
                newArea.splice(0, newArea.length, name);
            } else if (this.currentTab === 1) {
                // 选择城市时，清空区县
                if (newArea.length < 2) {
                    newArea.push(name);
                } else {
                    newArea[1] = name;
                    newArea.splice(2);
                }
            } else {
                // 选择区县
                if (newArea.length < 3) {
                    newArea.push(name);
                } else {
                    newArea[2] = name;
                }
            }
            
            this.formData.area = newArea;
            
            // 自动切换到下一级标签页
            if (this.currentTab < 2 && this.currentList.some(item => item.name === name)) {
                this.changeTab(this.currentTab + 1);
            }
        },
        
        // 判断地区是否已选择
        isSelected(name) {
            return this.formData.area[this.currentTab] === name;
        }
    }
}
</script>

<style>
/* 地址管理页面样式 */
.address-container {
    padding: 20rpx;
    background-color: #f8f8f8;
    min-height: 100vh;
}

/* 地址列表 */
.address-list {
    margin-bottom: 20rpx;
}

.address-item {
    background-color: #fff;
    border-radius: 12rpx;
    padding: 30rpx;
    margin-bottom: 20rpx;
    position: relative;
}

.address-item.active::before {
    content: "";
    position: absolute;
    left: 0;
    top: 0;
    bottom: 0;
    width: 6rpx;
    background-color: #E64340;
    border-radius: 6rpx 0 0 6rpx;
}

.name-phone {
    display: flex;
    justify-content: space-between;
    margin-bottom: 15rpx;
}

.name {
    font-size: 34rpx;
    font-weight: 500;
    color: #333;
}

.phone {
    font-size: 30rpx;
    color: #666;
}

.address-detail {
    font-size: 30rpx;
    color: #666;
    line-height: 1.5;
}

.detail {
    margin-left: 10rpx;
    color: #333;
}

.address-actions {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 20rpx;
}

.default-tag {
    font-size: 24rpx;
    color: #E64340;
    background-color: #ffebeb;
    padding: 4rpx 12rpx;
    border-radius: 4rpx;
}

.edit-delete {
    display: flex;
    color: #999;
    font-size: 28rpx;
}

.edit-delete text {
    margin-left: 40rpx;
}

/* 空地址提示 */
.empty-address {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding-top: 160rpx;
}

.empty-address image {
    width: 240rpx;
    height: 240rpx;
    margin-bottom: 40rpx;
}

.empty-address text {
    font-size: 30rpx;
    color: #999;
    margin-bottom: 60rpx;
}

.add-btn {
    background-color: #E64340;
    color: #fff;
    font-size: 32rpx;
    width: 400rpx;
    height: 88rpx;
    line-height: 88rpx;
    text-align: center;
    border-radius: 44rpx;
}

/* 添加/编辑地址弹窗 */
.address-modal {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    z-index: 1000;
    display: flex;
    justify-content: center;
    align-items: center;
}

.modal-content {
    background-color: #fff;
    width: 670rpx;
    border-radius: 16rpx;
    overflow: hidden;
}

.modal-header {
    height: 90rpx;
    line-height: 90rpx;
    text-align: center;
    font-size: 34rpx;
    font-weight: 500;
    color: #333;
    position: relative;
    border-bottom: 1rpx solid #eee;
}

.modal-header .close {
    position: absolute;
    right: 30rpx;
    top: 0;
    font-size: 40rpx;
    color: #999;
}

.modal-body {
    padding: 30rpx;
}

.form-item {
    display: flex;
    align-items: center;
    padding: 20rpx 0;
    border-bottom: 1rpx solid #eee;
}

.form-item:last-child {
    border-bottom: none;
}

.form-item text {
    width: 160rpx;
    font-size: 30rpx;
    color: #333;
}

.form-item input,
.form-item textarea {
    flex: 1;
    font-size: 30rpx;
    color: #666;
    min-height: 40rpx;
}

.form-item textarea {
    padding: 10rpx 0;
    line-height: 1.5;
}

.area-select {
    position: relative;
}

.selected-area {
    flex: 1;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.selected-area text {
    width: auto;
    color: #666;
}

.selected-area image {
    width: 24rpx;
    height: 14rpx;
}

.checkbox {
    padding-left: 160rpx;
}

.modal-footer {
    padding: 30rpx;
}

.save-btn {
    background-color: #E64340;
    color: #fff;
    font-size: 32rpx;
    height: 88rpx;
    line-height: 88rpx;
    text-align: center;
    border-radius: 44rpx;
}

/* 地区选择器 */
.area-picker {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: #fff;
    z-index: 2000;
    max-height: 70vh;
    display: flex;
    flex-direction: column;
}

.picker-header {
    display: flex;
    justify-content: space-between;
    padding: 25rpx 30rpx;
    border-bottom: 1rpx solid #eee;
}

.picker-header text {
    font-size: 30rpx;
    color: #333;
}

.picker-tabs {
    display: flex;
    border-bottom: 1rpx solid #eee;
}

.tab {
    flex: 1;
    text-align: center;
    height: 90rpx;
    line-height: 90rpx;
    font-size: 30rpx;
    color: #666;
    position: relative;
}

.tab.active {
    color: #E64340;
    font-weight: 500;
}

.tab.active::after {
    content: "";
    position: absolute;
    bottom: 0;
    left: 50%;
    transform: translateX(-50%);
    width: 60rpx;
    height: 6rpx;
    background-color: #E64340;
    border-radius: 3rpx;
}

.picker-content {
    flex: 1;
    overflow: hidden;
}

.area-list {
    max-height: calc(70vh - 270rpx);
    padding: 0 30rpx;
}

.area-item {
    height: 90rpx;
    line-height: 90rpx;
    font-size: 30rpx;
    color: #333;
    border-bottom: 1rpx solid #eee;
}

.area-item:last-child {
    border-bottom: none;
}

.area-item.selected {
    color: #E64340;
    position: relative;
}

.area-item.selected::after {
    content: "✓";
    position: absolute;
    right: 0;
    top: 0;
    font-size: 36rpx;
}

/* 添加地址按钮 */
.add-address-btn {
    position: fixed;
    bottom: 60rpx;
    left: 50%;
    transform: translateX(-50%);
    background-color: #E64340;
    color: #fff;
    font-size: 32rpx;
    width: 670rpx;
    height: 88rpx;
    line-height: 88rpx;
    text-align: center;
    border-radius: 44rpx;
    box-shadow: 0 10rpx 20rpx rgba(255, 170, 255, 0.2);
}
</style>    